package com.tang.controller;

import com.tang.pojo.ScheduleJob;
import com.tang.service.JobTaskService;
import com.tang.support.RetObj;
import com.tang.support.spring.SpringUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.quartz.CronScheduleBuilder;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

/**
 * 定时任务
 *
 * @author 唐一菲
 */
@RestController
@SuppressWarnings({"rawtypes", "unused", "unchecked"})
public class JobTaskController {

    // 日志记录器
    private static final Logger logger = LogManager.getLogger(JobTaskController.class);

    @Autowired
    private JobTaskService taskService;

    /**
     * 添加定时作业任务
     *
     * @param request
     * @param scheduleJob
     * @return
     */
    @RequestMapping("/task/add")
    public RetObj taskAdd(HttpServletRequest request, ScheduleJob scheduleJob) {
        RetObj retObj = new RetObj();
        retObj.setFlag(false);
        try {
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(scheduleJob.getCronExpression());
        } catch (Exception e) {
            retObj.setMsg("cron表达式有误，不能被解析！");
            return retObj;
        }
        Object obj = null;
        try {
            if (StringUtils.isNotBlank(scheduleJob.getSpringId())) {
                obj = SpringUtils.getBean(scheduleJob.getSpringId());
            } else {
                Class<?> clazz = Class.forName(scheduleJob.getBeanClass());
                obj = clazz.newInstance();
            }
        } catch (Exception e) {
            // do nothing.........
        }
        if (obj == null) {
            retObj.setMsg("未找到目标类！");
            return retObj;
        } else {
            Class clazz = obj.getClass();
            Method method = null;
            try {
                method = clazz.getMethod(scheduleJob.getMethodName(), null);
            } catch (Exception e) {
                // do nothing.....
            }
            if (method == null) {
                retObj.setMsg("未找到目标方法！");
                return retObj;
            }
        }
        try {
            taskService.addTask(scheduleJob);
        } catch (Exception e) {
            e.printStackTrace();
            retObj.setFlag(false);
            retObj.setMsg("保存失败，检查 name group 组合是否有重复！");
            return retObj;
        }
        retObj.setFlag(true);
        return retObj;
    }

    /**
     * 改变作业任务状态
     *
     * @param request
     * @param jobId
     * @param cmd
     * @return
     */
    @RequestMapping("/task/changeJobStatus")
    public RetObj changeJobStatus(HttpServletRequest request, Long jobId, String cmd) {
        RetObj retObj = new RetObj();
        retObj.setFlag(false);
        try {
            taskService.changeStatus(jobId, cmd);
        } catch (SchedulerException e) {
            logger.error(e.getMessage(), e);
            retObj.setMsg("任务状态改变失败！");
            return retObj;
        }
        retObj.setFlag(true);
        return retObj;
    }

    /**
     * 更新运行时间表达式
     *
     * @param request
     * @param jobId
     * @param cron
     * @return
     */
    @RequestMapping("/task/updateCron")
    public RetObj updateCron(HttpServletRequest request, Long jobId, String cron) {
        RetObj retObj = new RetObj();
        retObj.setFlag(false);
        try {
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cron);
        } catch (Exception e) {
            retObj.setMsg("cron表达式有误，不能被解析！");
            return retObj;
        }
        try {
            taskService.updateCron(jobId, cron);
        } catch (SchedulerException e) {
            retObj.setMsg("cron更新失败！");
            return retObj;
        }
        retObj.setFlag(true);
        return retObj;
    }

    /**
     * 立即运行某个作业任务
     *
     * @param jobId 作业主键
     * @return
     */
    @RequestMapping(value = "/task/executePauseJobNow")
    public RetObj executePauseJobNow(Long jobId, String cmd) {
        RetObj retObj = new RetObj();
        retObj.setFlag(false);
        try {
            taskService.executePauseJobNow(jobId, cmd);
        } catch (SchedulerException e) {
            retObj.setMsg("立即运行某个作业失败！");
            return retObj;
        }
        retObj.setFlag(true);
        return retObj;
    }

}
